<?php

/**
 * 数据操作
 *
 * php /path/aishang/index.php top auto
 *
 * @author 
 */
if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}
include_once APPPATH . "libraries/ExceptionHandler.php";
include_once APPPATH . "core/base_controller.php";
class autopush extends base_controller {

    var $taobaoclient = null;

    public function __construct() {
        parent::__construct();
        $this->load->library('ApachSdk');
        $this->load->model('orderpushmodel');
        $this->load->model('authorizetokenmodel'); //授权表

        $this->load->library('queue', array('key'=>'wait_push_queue')); //队列
    }

    /*
     *  消费队列push消息
     *  add by tongxiaoyong     
     */
    public function consumption() {
        set_time_limit(0);
        $apclient = new APClient();
        $starttime = time();
        while (true) {
            try {
                $seri_str = $this->queue->pop();
                $nowtime = time();
                if($nowtime-$starttime > 60){
                    $this->authorizetokenmodel->getToken(0, 1);//防止mysql断开
                    $starttime = $nowtime;
                }
                if (!$seri_str) {
                    continue;
                }
                echo $seri_str . "\n";
                $queue = unserialize($seri_str);
                if (!$queue || !isset($queue['order_id']) || !isset($queue['user_id'])) {
                    continue;
                }
                if($queue['push_time'] < date('Y-m-d H:i:s')){
                    $order_pushed = $this->orderpushmodel->getOrderById($queue['order_id']);
                    if(!$order_pushed){
                        echo $apclient->api('/apach/auto_pushed/',array(
                            'order_id' => $queue['order_id'],
                            'user_id' => $queue['huaji_user_id'],
                            'sign_key' => md5($queue['order_id'].$queue['huaji_user_id'].'123456!we3##')
                        ))."\n";
                    }
                }else{
                   $this->queue->push($seri_str); 
                }
            } catch (Exception $e) {
                echo 'Caught exception: ', $e->getMessage(), "\n";
            }
            usleep(5000);
        }
    }
   
}
